﻿
using PdfiumViewer;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using 卷书.UserControls;
using 卷书.Utils;
using static 卷书.Global;
using Microsoft.WindowsAPICodePack.Dialogs;
using 卷书.SQL;

namespace 卷书
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public enum MyWindowState { Normal, Minimized, Maximized, FullScreen, None }

        private MyWindowState myWindowState = MyWindowState.Normal;
        public Point WindowPoint = new Point(100, 100);
        public Size WindowSize = new Size(1000, 600);

        private HwndSource _hwndSource;
        private bool _IsMenuChecked = false;
        public bool IsMenuChecked
        {
            get
            {
                return _IsMenuChecked;
            }
            set
            {
                _IsMenuChecked = value;
                if (value)
                {
                    ShowMenu("", true);
                    foreach (var item in MenuStackPanel.Children.OfType<CheckBox>().ToList())
                    {
                        item.IsChecked = true;
                    }
                }
                else
                {
                    ShowMenu("", false); ;
                    foreach (var item in MenuStackPanel.Children.OfType<CheckBox>().ToList())
                    {
                        item.IsChecked = false;
                    }
                    RecentGrid.Visibility = Visibility.Collapsed;
                }
            }
        }


        private bool _IsSideMenuChecked = true;
        public bool IsSideMenuChecked
        {
            get
            {
                return _IsSideMenuChecked;
            }
            set
            {
                _IsSideMenuChecked = value;
                if (value) SideMenu.Visibility = Visibility.Collapsed;
                else SideMenu.Visibility = Visibility.Visible;
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            Settings.Instance.Init();
            Settings.CurrentProjectChanged += (s, e) =>
            {
                if (File.Exists(Settings.CurrentProject))
                {
                    TitleTextBlock.Text = System.IO.Path.GetFileNameWithoutExtension(Settings.CurrentProject) + " - 卷书";
                    Global.Init();
                    //添加到最近中，覆盖最老的
                    

                    if (!Settings.RecentProject.Contains(Settings.CurrentProject))
                    {
                        if (Settings.RecentProject.Count == 10)
                            Settings.RecentProject.RemoveAt(9);
                        Settings.RecentProject.Insert(0,Settings.CurrentProject);
                    }



                }
                else
                {
                    TitleTextBlock.Text = "卷书";
                }
            };
            InitDataBase();
            InitLibrary();

            this.Width = SystemParameters.PrimaryScreenWidth / 3 *2 ;
            this.Height = SystemParameters.PrimaryScreenHeight / 3 * 2;
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;




            #region "改变窗体大小"
            //https://www.cnblogs.com/yang-fei/p/4737308.html

            if (resizeGrid != null)
            {
                foreach (UIElement element in resizeGrid.Children)
                {
                    if (element is Rectangle resizeRectangle)
                    {
                        resizeRectangle.PreviewMouseDown += ResizeRectangle_PreviewMouseDown;
                        resizeRectangle.MouseMove += ResizeRectangle_MouseMove;
                    }
                }
            }
            PreviewMouseMove += OnPreviewMouseMove;
            #endregion
        }

        #region "改变窗体大小"
        private void ResizeRectangle_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized) return;
            if (this.Width == SystemParameters.WorkArea.Width || this.Height == SystemParameters.WorkArea.Height) return;

            if (sender is Rectangle rectangle)
            {
                switch (rectangle.Name)
                {
                    case "TopRectangle":
                        Cursor = Cursors.SizeNS;
                        ResizeWindow(ResizeDirection.Top);
                        break;
                    case "Bottom":
                        Cursor = Cursors.SizeNS;
                        ResizeWindow(ResizeDirection.Bottom);
                        break;
                    case "LeftRectangle":
                        Cursor = Cursors.SizeWE;
                        ResizeWindow(ResizeDirection.Left);
                        break;
                    case "Right":
                        Cursor = Cursors.SizeWE;
                        ResizeWindow(ResizeDirection.Right);
                        break;
                    case "TopLeft":
                        Cursor = Cursors.SizeNWSE;
                        ResizeWindow(ResizeDirection.TopLeft);
                        break;
                    case "TopRight":
                        Cursor = Cursors.SizeNESW;
                        ResizeWindow(ResizeDirection.TopRight);
                        break;
                    case "BottomLeft":
                        Cursor = Cursors.SizeNESW;
                        ResizeWindow(ResizeDirection.BottomLeft);
                        break;
                    case "BottomRight":
                        Cursor = Cursors.SizeNWSE;
                        ResizeWindow(ResizeDirection.BottomRight);
                        break;
                    default:
                        break;
                }
            }
        }


        protected void OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.LeftButton != MouseButtonState.Pressed)
                Cursor = Cursors.Arrow;
        }

        private void ResizeRectangle_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized) return;
            if (this.Width == SystemParameters.WorkArea.Width || this.Height == SystemParameters.WorkArea.Height) return;

            if (sender is Rectangle rectangle)
            {
                switch (rectangle.Name)
                {
                    case "TopRectangle":
                        Cursor = Cursors.SizeNS;
                        break;
                    case "Bottom":
                        Cursor = Cursors.SizeNS;
                        break;
                    case "LeftRectangle":
                        Cursor = Cursors.SizeWE;
                        break;
                    case "Right":
                        Cursor = Cursors.SizeWE;
                        break;
                    case "TopLeft":
                        Cursor = Cursors.SizeNWSE;
                        break;
                    case "TopRight":
                        Cursor = Cursors.SizeNESW;
                        break;
                    case "BottomLeft":
                        Cursor = Cursors.SizeNESW;
                        break;
                    case "BottomRight":
                        Cursor = Cursors.SizeNWSE;
                        break;
                    default:
                        break;
                }
            }
        }

        public enum ResizeDirection
        {
            Left = 1,
            Right = 2,
            Top = 3,
            TopLeft = 4,
            TopRight = 5,
            Bottom = 6,
            BottomLeft = 7,
            BottomRight = 8,
        }

        protected override void OnInitialized(EventArgs e)
        {
            SourceInitialized += MainWindow_SourceInitialized;
            base.OnInitialized(e);
        }

        private void MainWindow_SourceInitialized(object sender, EventArgs e)
        {
            _hwndSource = (HwndSource)PresentationSource.FromVisual(this);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);

        private void ResizeWindow(ResizeDirection direction)
        {
            SendMessage(_hwndSource.Handle, 0x112, (IntPtr)(61440 + direction), IntPtr.Zero);
        }

        #endregion


        private void InitDataBase()
        {
            if (!File.Exists(Global.SqlitePath))
            {
                SqliteStream db = new SqliteStream(Global.SqlitePath);
                db.RunSql(SqliteStream.SQLITETABLE_BASIC);
                db.RunSql(SqliteStream.SQLITETABLE_DEGREE);
                db.RunSql(SqliteStream.SQLITETABLE_JOURNALARTICLE);
                db.CloseDB();
            }
        }

        private void InitLibrary()
        {

            LibrariesContainer.Children.Clear();
            Global.Init();
            foreach (var item in Libraries)
            {
                LibraryView libraryView = new LibraryView(item.Name);
                LibrariesContainer.Children.Add(libraryView);
            }
            
            pdfViewer.Source = "";
            pdfViewer.Init();
            if (TitleTextBlock != null && File.Exists(Settings.CurrentProject))
            {

                NewLibraryBtn.IsEnabled = true;
            }

        }

        private void MinWindow(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
            this.DataContext = this;
        }

        private void MaxWindow(object sender, MouseButtonEventArgs e)
        {
            if (myWindowState == 0)
            {
                //最大化
                myWindowState = MyWindowState.Maximized;
                WindowPoint = new Point(this.Left, this.Top);
                WindowSize = new Size(this.Width, this.Height);
                this.Width = SystemParameters.WorkArea.Width;
                this.Height = SystemParameters.WorkArea.Height;
                this.Top = SystemParameters.WorkArea.Top;
                this.Left = SystemParameters.WorkArea.Left;
            }
            else
            {
                myWindowState = MyWindowState.Normal;
                this.Left = WindowPoint.X;
                this.Width = WindowSize.Width;
                this.Top = WindowPoint.Y;
                this.Height = WindowSize.Height;
            }
            this.WindowState = WindowState.Normal;
            this.OnLocationChanged(EventArgs.Empty);
            HideMargin();
        }

        private void HideMargin()
        {
            if (myWindowState == MyWindowState.Normal)
            {
                MainGrid.Margin = new Thickness(10);
                MainBorder.Margin = new Thickness(5);
                this.ResizeMode = ResizeMode.CanResize;
            }
            else if (myWindowState == MyWindowState.Maximized || this.WindowState == WindowState.Maximized)
            {
                MainGrid.Margin = new Thickness(0);
                MainBorder.Margin = new Thickness(0);
                this.ResizeMode = ResizeMode.NoResize;
            }
        }

        private void CloseWindow(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void MoveWindow(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && canDragWindow)
            {
                if (this.WindowState == WindowState.Maximized || (this.Width == SystemParameters.WorkArea.Width && this.Height == SystemParameters.WorkArea.Height))
                {
                    Border border = sender as Border;
                    myWindowState = 0;
                    double fracWidth = e.GetPosition(border).X / border.ActualWidth;
                    this.Width = WindowSize.Width;
                    this.Height = WindowSize.Height;
                    this.WindowState = WindowState.Normal;
                    this.Left = e.GetPosition(border).X - border.ActualWidth * fracWidth;
                    this.Top = e.GetPosition(border).Y - border.ActualHeight / 2;
                    this.OnLocationChanged(EventArgs.Empty);
                    HideMargin();
                }

                this.DragMove();
            }
        }

        private void SetMenuChecked(object sender, RoutedEventArgs e)
        {

            ToggleButton btn = sender as ToggleButton;

            IsMenuChecked = (bool)btn.IsChecked;
            if (IsMenuChecked)
            {
                ShowMenu(btn.Content.ToString(), true);
            }

        }



        private void ShowContextMenu(object sender, MouseEventArgs e)
        {
            if (IsMenuChecked)
            {
                ShowMenu(((CheckBox)sender).Content.ToString(), true); ;
            }
        }

        private void ShowMenu(string name, bool visble)
        {
            Visibility visibility;
            if (visble)
                visibility = Visibility.Visible;
            else
                visibility = Visibility.Hidden;
            MenuStackPanel.Children.OfType<CheckBox>().ToList().ForEach(arg => arg.Background = Brushes.Transparent);
            FileMenu.Visibility = Visibility.Hidden;
            EditMenu.Visibility = Visibility.Hidden;
            HelpMenu.Visibility = Visibility.Hidden;
            RecentGrid.Visibility = Visibility.Collapsed;
            switch (name)
            {
                case "文件":
                    FileMenu.Visibility = visibility;
                    MenuStackPanel.Children.OfType<CheckBox>().First().Background = Brushes.Gray;
                    break;

                case "库":
                    EditMenu.Visibility = visibility;
                    MenuStackPanel.Children.OfType<CheckBox>().ToList()[1].Background = Brushes.Gray;
                    break;

                case "帮助":
                    HelpMenu.Visibility = visibility;
                    MenuStackPanel.Children.OfType<CheckBox>().Last().Background = Brushes.Gray;
                    break;

                default:

                    break;
            }
        }

        private bool canDragWindow = false;
        private void DragMoveWindow(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;

            if (e.ClickCount > 1)
            {
                MaxWindow(sender, null);
            }
            canDragWindow = true;
        }

        private void DisableMenuChecked(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
        }

        private void Window_ContentRendered(object sender, EventArgs e)
        {
            Panel.SetZIndex(resizeGrid, 10);
            if (Libraries == null) Libraries = new List<Library>();
            if (Libraries.Count > 0)
            {
                WelCome.Visibility = Visibility.Collapsed;
            }
            //pdfViewer.Source = @"C:\Users\chao\Desktop\顶刊-图神经网络.pdf";

            TitleTextBlock.Text = System.IO.Path.GetFileNameWithoutExtension(Settings.CurrentProject) + " - 卷书";
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (this.Width == SystemParameters.WorkArea.Width || this.Height == SystemParameters.WorkArea.Height)
            {
                MainGrid.Margin = new Thickness(0);
                MainBorder.Margin = new Thickness(0);
                Grid.Margin = new Thickness(0);
                this.ResizeMode = ResizeMode.NoResize;
            }
            else if (this.WindowState == WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal;
                myWindowState = MyWindowState.Normal;
                MaxWindow(this, null);
            }
            else
            {
                MainGrid.Margin = new Thickness(10);
                MainBorder.Margin = new Thickness(5);
                Grid.Margin = new Thickness(5);
                this.ResizeMode = ResizeMode.CanResize;
            }

            MaxSideMenuWidth = e.NewSize.Width / 2;
        }

        private void FileMenu_MouseEnter(object sender, MouseEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            MenuStackPanel.Children.OfType<CheckBox>().ToList().ForEach(arg => arg.Background = Brushes.Transparent);

            switch (element.Name)
            {
                case "FileMenu":
                    MenuStackPanel.Children.OfType<CheckBox>().First().Background = Brushes.Gray;
                    break;

                case "EditMenu":
                    MenuStackPanel.Children.OfType<CheckBox>().ToList()[1].Background = Brushes.Gray;
                    break;

                case "HelpMenu":
                    MenuStackPanel.Children.OfType<CheckBox>().Last().Background = Brushes.Gray;
                    break;

                default:

                    break;
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void ShowSideMenu(string name)
        {
            if (SideMenu != null)
            {
                switch (name)
                {
                    case "库":
                        SideMenu.SelectedIndex = 0;
                        break;


                    case "搜索":
                        SideMenu.SelectedIndex = 1;
                        break;

                    default:


                        break;
                }
            }


        }

        private void HideSideMenu(object sender, RoutedEventArgs e)
        {
            SideMenu.Visibility = Visibility.Collapsed;
        }

        private void SetSideMenuChecked(object sender, RoutedEventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            SideCheckBoxes.Children.OfType<CheckBox>().ToList().Where(arg => arg != checkBox).ToList().ForEach(arg => arg.IsChecked = false);
            if ((bool)checkBox.IsChecked)
            {
                IsSideMenuChecked = false;
            }
            else
            {
                IsSideMenuChecked = true;
            }

            ShowSideMenu(checkBox.Content.ToString());

        }

        private bool IsDragingSideMenu = false;
        private double SideMenuWidth = 200;
        private double MinSideMenuWidth = 150;
        private double _MaxSideMenuWidth = 500;

        private double MaxSideMenuWidth
        {
            get
            {
                return _MaxSideMenuWidth;
            }
            set
            {
                _MaxSideMenuWidth = value;
                if (SideMenu.Width > value)
                {
                    SideMenu.Width = value;
                    SideMenuWidth = value;
                }
            }
        }

        private void DragRectangle_MouseMove(object sender, MouseEventArgs e)
        {
            if (SideMenuWidth >= MinSideMenuWidth) { if (sender is Rectangle rectangle) rectangle.Cursor = Cursors.SizeWE; }
            if (IsDragingSideMenu)
            {
                this.Cursor = Cursors.SizeWE;
                double width = e.GetPosition(SideMenu).X;
                if (width < MinSideMenuWidth)
                {
                    SideMenuWidth = MinSideMenuWidth;
                }
                else if( width> MaxSideMenuWidth)
                {
                    SideMenuWidth = MaxSideMenuWidth;
                }
                else
                {
                    SideMenuWidth = width;
                }
                SideMenu.Width = SideMenuWidth;

            }
        }

        private void DragRectangle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                IsDragingSideMenu = true;
            }
        }

        private void DragRectangle_MouseUp(object sender, MouseButtonEventArgs e)
        {
            IsDragingSideMenu = false;
            
        }

        private void SideMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ShowAbout(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;

            new Dialog_About(this, false).ShowDialog();
        }

        private void TreeView_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (sender is TreeView && !e.Handled)
            {
                e.Handled = true;
                var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
                eventArg.RoutedEvent = UIElement.MouseWheelEvent;
                eventArg.Source = sender;
                var parent = ((Control)sender).Parent as UIElement;
                parent.RaiseEvent(eventArg);
            }
        }

        private async void NewLibrary(object sender, RoutedEventArgs e)
        {
            if (!NewLibraryBtn.IsEnabled) return;
            LibraryView libraryView = new LibraryView(GetName());
            Library library = new Library(libraryView.LibraryName);
            library.CreateDate = DateTime.Now;
            LibrariesContainer.Children.Add(libraryView);
            Libraries.Add(new Library() { Name = libraryView.LibraryName });
            var textBox = LogicalTreeHelper.FindLogicalNode(libraryView, "tb");
            if (textBox != null)
            {
                await Task.Delay(100);
                TextBox tb = textBox as TextBox;
                tb.Visibility = Visibility.Visible;
                
                tb.SelectAll();
                tb.Focus();
            }
            //保存
            new LibraryStream(library,Settings.CurrentProject);
            Global.Init();

        }

        private string GetName()
        {
            if (Libraries == null) return "我的库";
            List<string> names = Libraries.Select(arg => arg.Name).ToList();
            if (!names.Contains("我的库"))
            {
                return "我的库";
            }
            else
            {
                int max = 1;
                names.Where(arg => arg.IndexOf("我的库") >= 0).ToList().ForEach(arg=> {
                    int.TryParse(arg.Replace("我的库", ""), out int v);
                    if (v > max) max = v;
                });
                max++;
                return "我的库" + max;
            }
        }

        private void DeleteLibrary(object sender, RoutedEventArgs e)
        {
            //MenuItem item = sender as MenuItem;
            //ContextMenu contextMenu = item.Parent as ContextMenu;
            //myTreeView.Items.Remove((TreeViewItem)contextMenu.PlacementTarget);
        }

        private void ClearFocus(object sender, MouseButtonEventArgs e)
        {
            FocusTextBox.Focus();
            IsMenuChecked = false;
        }

        private void NewProject(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.FileName = "新项目.volumebook";
            dialog.Title = "新建项目";
            dialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            dialog.Filter = "volumebook|*.volumebook";
            dialog.FilterIndex = 1;
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //初始化一个 项目文件
                new LibraryStream(dialog.FileName).InitXML(true);
                Settings.CurrentProject = dialog.FileName;
                Settings.Instance.SaveAllSetting();
                InitLibrary();
            }
        }

        private void ExpandAllLibrary(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            List<LibraryView> lvs;
            if (SideMenu.SelectedIndex == 0)
            {
                 lvs = LibrariesContainer.Children.OfType<LibraryView>().ToList();
            }
            else
            {
                 lvs = SearchResultContainer.Children.OfType<LibraryView>().ToList();
            }
            foreach (LibraryView item in lvs)
            {
                CheckBox checkBox = LogicalTreeHelper.FindLogicalNode(item, "cb") as CheckBox;
                checkBox.IsChecked = true;
            }
        }

        private void PackUpAllLibrary(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            List<LibraryView> lvs;
            if (SideMenu.SelectedIndex == 0)
            {
                lvs = LibrariesContainer.Children.OfType<LibraryView>().ToList();
            }
            else
            {
                lvs = SearchResultContainer.Children.OfType<LibraryView>().ToList();
            }
            foreach (LibraryView item in lvs)
            {
                CheckBox checkBox = LogicalTreeHelper.FindLogicalNode(item, "cb") as CheckBox;
                checkBox.IsChecked = false;
            }
        }

        private async void ImportDirAsLibrary(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            if (!NewLibraryBtn.IsEnabled) return;
            SideMenu.SelectedIndex = 0;
            SideCheckBoxes.Children.OfType<CheckBox>().First().IsChecked = true;
            SideCheckBoxes.Children.OfType<CheckBox>().Last().IsChecked = false;


            var dialog = new CommonOpenFileDialog();
            dialog.Title = "选择文件夹";
            dialog.IsFolderPicker = true;
            dialog.InitialDirectory= AppDomain.CurrentDomain.BaseDirectory;
            if( dialog.ShowDialog()== CommonFileDialogResult.Ok)
            {
                string path = dialog.FileName;
                try
                {
                    string[] files =  System.IO.Directory.GetFiles(path, "*.pdf", System.IO.SearchOption.TopDirectoryOnly);
                    NewLibrary(this, null);
                    await Task.Delay(100);
                    if (files != null && files.Length > 0)
                    {
                        LibraryView libraryView = LibrariesContainer.Children.OfType<LibraryView>().Last();
                        libraryView.ImportFile(files);
                    }
                }
                catch (Exception ex)
                {
                    StatusMessage = new System.Text.StringBuilder(ex.Message);
                    Logger.LogF(ex);
                }
            }

        }

        private void SearchLibrary(object sender, TextChangedEventArgs e)
        {
            if (SearchResultTextBlock == null) return;
            string search = SearchTextBox.Text;
            if (search == "")
            {
                SearchResultTextBlock.Text = "请输入搜索内容";
                hintTextBlock.Text = "搜索";
                SearchResultContainer.Children.Clear();
            }
            else
            {
                hintTextBlock.Text = "";
                SearchResultContainer.Children.Clear();
                

                //配置搜索选项
                var tbtns = SearchOptionStackPanel.Children.OfType<ToggleButton>().ToList();
                Regex regex ;
                if ((bool)tbtns[0].IsChecked)
                     regex = new Regex(search);
                else
                    regex = new Regex(search, RegexOptions.IgnoreCase);


                List<string> result = new List<string>();
                foreach (LibraryView lv in LibrariesContainer.Children.OfType<LibraryView>().ToList())
                {
                    if (lv.LibraryList.Where(arg => regex.Match(arg.filename).Success).Any() || regex.Match(lv.LibraryName).Success || lv.LibraryList.Where(arg => regex.Match(string.Join("",arg.tags)).Success).Any() || lv.LibraryList.Where(arg => regex.Match(arg.descriptions).Success).Any())
                    {
                        if ((bool)tbtns[1].IsChecked)
                        {
                            //全词匹配
                            if (search.Length == lv.LibraryName.Length)
                            {
                                result.Add(lv.LibraryName);
                            }
                            else
                            {
                                if(lv.LibraryList.Where(arg => arg.filename.Length==search.Length).Any())
                                {
                                    result.Add(lv.LibraryName);
                                }
                            }
                        }
                        else
                        {
                            result.Add(lv.LibraryName);
                        }
                            
                    }

                }
                foreach (var item in result)
                {
                    LibraryView libraryView = new LibraryView(item);
                    SearchResultContainer.Children.Add(libraryView);
                }
                SearchResultTextBlock.Text = $"在 {result.Count} 个库中找到以下个结果";
            }


        }

        private void SetTextBoxFocus(object sender, MouseButtonEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            TextBox textBox = (tb.Parent as Grid).Children.OfType<TextBox>().First();
            textBox.Focus();
        }

        private void ToggleButton_Click(object sender, RoutedEventArgs e)
        {
            SearchLibrary(this, null);
        }

        private void TopBorder_MouseLeave(object sender, MouseEventArgs e)
        {
            canDragWindow = false;
        }

        private void TopBorder_MouseUp(object sender, MouseButtonEventArgs e)
        {
            canDragWindow = false;
        }

        private void SaveAs(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.FileName = "我的项目.volumebook";
            dialog.Title = "项目另存为";
            dialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            dialog.Filter = "volumebook|*.volumebook";
            dialog.FilterIndex = 1;
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string targetPath = dialog.FileName;
                File.Copy(Settings.CurrentProject,targetPath);
            }
        }

        private void OpenProject(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            System.Windows.Forms.OpenFileDialog OpenFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            OpenFileDialog1.Title = "请选择文件";
            OpenFileDialog1.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            OpenFileDialog1.Filter = "volumebook|*.volumebook";
            OpenFileDialog1.FilterIndex = 1;
            OpenFileDialog1.RestoreDirectory = true;
            OpenFileDialog1.Multiselect = true;
            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Settings.CurrentProject = OpenFileDialog1.FileName;
                Settings.Instance.SaveAllSetting();
                InitLibrary();
            }

        }

        private void CloseProject(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            pdfViewer.Source = "";
            pdfViewer.Init();
            LibrariesContainer.Children.Clear();
            Settings.CurrentProject = "";
            Settings.Instance.SaveAllSetting();
            NewLibraryBtn.IsEnabled = false;
        }

        private void RenameProject(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            if (!File.Exists(Settings.CurrentProject)) return;
            string parent = System.IO.Path.GetDirectoryName(Settings.CurrentProject);
            var r =new Dialog_Input(this, true, Settings.CurrentProject);
            if (r.ShowDialog() == true)
            {
                
                string text = r.InputText;
                foreach (var item in BANFILECHAR)
                {
                    text.Replace(item.ToString(),"");
                }

                string newname = System.IO.Path.Combine(parent, text + ".volumebook");
                if (File.Exists(newname))
                {
                    StatusMessage = new System.Text.StringBuilder("文件已存在！");
                }
                else
                {
                    File.Move(Settings.CurrentProject,newname);
                    Settings.CurrentProject = newname;
                    Settings.Instance.SaveAllSetting();
                }




            }
        }

        private void CreateNewLibrary(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;
            NewLibrary(null, null);
        }

        private void ShowRecentPopup(object sender, MouseEventArgs e)
        {
            RecentGrid.Visibility = Visibility.Visible;
        }


        private void HideRecentPopup(object sender, MouseEventArgs e)
        {
            RecentGrid.Visibility = Visibility.Collapsed;
        }

        private void RecentGrid_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((sender as Grid).Visibility == Visibility.Visible)
            {
                RecentItemsControl.ItemsSource = Settings.RecentProject;
                RecentItemsControl.Items.Refresh();
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Settings.Instance.SaveAllSetting();
        }

        private void OpenRecent(object sender, MouseButtonEventArgs e)
        {
            IsMenuChecked = false;

            Grid grid = sender as Grid;
            string path = grid.Tag.ToString();
            Settings.CurrentProject = path;
            Settings.Instance.SaveAllSetting();
            InitLibrary();
        }
    }
}
